package szcg.main.service.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import szcg.framework.library.base.PostController;
import szcg.framework.library.entity.UserBean;
import szcg.main.service.service.UserService;

import java.util.HashMap;


@RestController
@RequestMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
public class MAIN_000_000_001 extends PostController {
    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_000_001.class);

    private final UserService userService;

    public MAIN_000_000_001(UserService userService) {
        this.userService = userService;
    }

    //登录接口
    @PostMapping(value = "/000_000_001")
    public String doPost(HttpServletRequest request) {
        return handleRequest(request);
    }

    @Override
    protected String postRequest(HashMap<String, String> param) {
        String requestBody = param.get("requestBody");
        JSONObject jsonObject = (JSONObject) JSON.parse(requestBody);
        String captchaKey = jsonObject.getString("captchaKey");
        String captcha = jsonObject.getString("captcha");
        String userName = jsonObject.getString("userName");
        String userPwd = jsonObject.getString("pwd");
        //用户->查库
        UserBean userBean = userService.getUserForName(userName);
        if (userBean == null) {
            return generateFail("用户不存在");
        }
        String pwd = userBean.userPwd;
        if (!pwd.equals(userPwd)) {
            return generateFail("密码错误");
        }
        //完成->颁发token
        Long userId = userBean.userId;
        String token = generateToken(String.valueOf(userId));
        //封装响应体
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("accessToken", token);
        resMap.put("userName", userBean.userName);
        return generateSucceed(resMap);
    }
}
